package mission_tour.solution;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class tour_login extends Activity implements ServerIp{
    /** Called when the activity is first created. */
	int c_sex = 0;
	String phonenumber = "";
	int c_result=0;
	ComponentName tService;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tour_login);
        
        final ImageButton login_btn = (ImageButton) findViewById(R.id.login_btn);
        final RadioButton man = (RadioButton) findViewById(R.id.man);
        final RadioButton woman = (RadioButton) findViewById(R.id.woman);
        
        Spinner phone_num1 = (Spinner) findViewById(R.id.phone_num1);
        final EditText phone_num2 = (EditText) findViewById(R.id.phone_num2);
        final EditText phone_num3 = (EditText) findViewById(R.id.phone_num3);
        
	    final ArrayAdapter mobile_adapter = ArrayAdapter.createFromResource(this, R.array.phone_num, android.R.layout.simple_spinner_item);
	    mobile_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    phone_num1.setAdapter(mobile_adapter);
		
	    phone_num1.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				//Toast.makeText(ClientInsertPage.this,(CharSequence) mobile_adapter.getItem(arg2),Toast.LENGTH_SHORT).show();
				phonenumber = (String) mobile_adapter.getItem(arg2);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
	    	
	    });
	    
        login_btn.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
					login_btn.setBackgroundResource(R.drawable.set_btn_down);
				}else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					login_btn.setBackgroundResource(R.drawable.set_btn);

					if(!man.isChecked() && !woman.isChecked()){
						Toast.makeText(tour_login.this,"성별을 선택 하여 주세요",Toast.LENGTH_SHORT).show();
					}else if(phone_num2.getText().toString().equals("") || phone_num3.getText().toString().equals("")){
						Toast.makeText(tour_login.this,"휴대폰 번호를 모두 입력하여 주세요",Toast.LENGTH_SHORT).show();
					}else{
						phonenumber += phone_num2.getText().toString()+phone_num3.getText().toString();
						
						if(man.isChecked()){
							c_sex = 1;
						}else{
							c_sex = 2;
						}
						AlertDialog.Builder nologin = new AlertDialog.Builder(tour_login.this);
						nologin.setTitle(items.appname);
						nologin.setMessage("사용자 등록을 하시 겠습니까?");
						nologin.setIcon(R.drawable.icon);
						nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								final ProgressDialog nowloding = ProgressDialog.show(tour_login.this,"","서버에 접속 하고 있습니다....",true);
								new Thread(new Runnable() {
									@Override
									public void run() {
										URL url = null;
								        
								        try {
								        	
								        	url = new URL(u_insert+"?mobile_num="+phonenumber+"&c_sex="+c_sex+"&app_type="+items.apptype);
								        	
									        HttpURLConnection http = (HttpURLConnection)url.openConnection();  
									
											BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
											StringBuffer buffer = new StringBuffer();
											 
											int z;  
											 
											while((z=in.read()) != -1){
												buffer.append((char)z);
											}
											
											String[] result = buffer.toString().trim().split(",");
											
											items.c_code = Integer.parseInt(result[0]);
											items.c_sex = Integer.parseInt(result[1]);
											items.c_point = Integer.parseInt(result[2]);
											c_result = Integer.parseInt(result[3]);
											
											SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE); // UI 상태를 저장합니다.
									    	SharedPreferences.Editor editor = pref.edit(); // Editor를 불러옵니다.

									        editor.putString("phone", phonenumber);	// 저장할 값들을 입력합니다.
									    
									    	editor.commit(); // 저장합니다.
									    	nowloding.cancel();	//프로그래스 종료
									    	startGPSservice(); //서비스 시작
									    	
									    	runOnUiThread(new Runnable(){
									            @Override
									             public void run() {
									            	AlertDialog.Builder insertok = new AlertDialog.Builder(tour_login.this);
											    	insertok.setTitle(items.appname);
											    	if(c_result == 0){
											    		insertok.setMessage("사용자 등록이 완료 되었습니다!");
											    	}else{
											    		insertok.setMessage("등록 되어 있는 고객입니다\n기존에 등록 하신 정보를 불러옵니다");
											    	}
											    	insertok.setIcon(R.drawable.icon);
											    	insertok.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
														@Override
														public void onClick(DialogInterface dialog, int which) {
															// TODO Auto-generated method stub
															Intent intent = new Intent(tour_login.this, tour_infomation_page.class);
						    								startActivityForResult(intent, 0);
						    								finish();
														}
													});
											    	insertok.show();
									             }
									        });
											
								        } catch (MalformedURLException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (IOException e) {
											// TODO Auto-generated catch block
							    			runOnUiThread(new Runnable(){
									            @Override
									             public void run() {
											    	nowloding.cancel();
									            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_login.this);
									    			nologin.setTitle(items.appname);
									    			nologin.setMessage("서버에 접속이 되지 않습니다\n잠시 후 다시 시도해 주세요");
									    			nologin.setIcon(R.drawable.icon);
									    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
									    				@Override
									    				public void onClick(DialogInterface dialog, int which) {
									    					// TODO Auto-generated method stub
									    					moveTaskToBack(true);
									    					android.os.Process.killProcess(android.os.Process.myPid());
									    				}
									    			});
									    			nologin.show();
									             }
									        });
											e.printStackTrace();
										}
									}
							    }).start();
							}
						});
						nologin.setNegativeButton("아니오", new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								AlertDialog.Builder exit_app = new AlertDialog.Builder(tour_login.this);
								exit_app.setTitle(items.appname);
								exit_app.setMessage("어플리케이션을 종료 합니다");
								exit_app.setIcon(R.drawable.icon);
								exit_app.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										moveTaskToBack(true);
										android.os.Process.killProcess(android.os.Process.myPid());
									}
								});
								exit_app.show();
								
							}
						});
						nologin.show();
					}
				}
					return false;
			}
		});
    }
    
    public boolean onKeyDown( int KeyCode, KeyEvent event ){
		if( event.getAction() == KeyEvent.ACTION_DOWN ){
			
			if( KeyCode == KeyEvent.KEYCODE_BACK ){
				items.back_push++;
				long currentTime = System.currentTimeMillis();
				if(items.back_push == 1){
					items.touchTime = System.currentTimeMillis();
					Toast t =  Toast.makeText(tour_login.this,"종료 하시려면\n한번 더 뒤로가기 버튼을 눌러주세요",Toast.LENGTH_SHORT);
				    t.setDuration(2000);
				    t.show();
				          
				    new Thread(new Runnable() {    
						@Override
						public void run() {
							try {
								Thread.sleep(2000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							items.back_push=0;
							}
				    	}).start();
				}else if(items.back_push == 2){
					if(currentTime - items.touchTime <= 2000 ){
						finish();
						return super.onKeyDown(KeyCode, event);
					}					
				}
				return true;
			}
		}
		return super.onKeyDown(KeyCode, event);
	}
    private void startGPSservice(){
    	tService = startService(new Intent(this,background_event_service.class));
    }
}